"""
股票投资总结智能体

综合技术、消息、估值、资金四大维度进行股票投资总结和建议。
"""

import json
from typing import Dict, Any, List, Optional
from .base_agent import BaseAgent, LLMConfig
from tools.stock_data_provider import stock_data_provider
from langchain_core.tools import Tool
import logging

# 导入其他维度智能体实例
from .stock_technical_analysis_agent import stock_technical_analysis_agent
from .stock_news_analysis_agent import stock_news_analysis_agent
from .stock_valuation_analysis_agent import stock_valuation_analysis_agent
from .stock_fundamental_analysis_agent import stock_fundamental_analysis_agent
from .stock_capital_flow_analysis_agent import stock_capital_flow_analysis_agent


class StockInvestmentSummaryAgent(BaseAgent):
    """股票投资总结智能体"""

    def __init__(self, llm_config: Optional[LLMConfig] = None):
        super().__init__(
            name="StockInvestmentSummaryAgent",
            description="股票投资总结智能体，综合多维度分析进行投资建议",
            llm_config=llm_config
        )
        self.logger = logging.getLogger(__name__)

    def get_tools(self) -> List[Tool]:
        """获取投资总结所需的工具"""
        return [
            Tool(
                name="aggregate_stock_analysis",
                description="汇总股票综合分析数据",
                func=self._aggregate_stock_analysis
            ),
            Tool(
                name="evaluate_investment_value",
                description="评估股票投资价值",
                func=self._evaluate_investment_value
            ),
            Tool(
                name="assess_risk_level",
                description="评估股票风险等级",
                func=self._assess_risk_level
            ),
            Tool(
                name="generate_investment_advice",
                description="生成投资建议",
                func=self._generate_investment_advice
            ),
            Tool(
                name="create_investment_report",
                description="创建投资分析报告",
                func=self._create_investment_report
            )
        ]

    def get_system_prompt(self) -> str:
        return """
        你是专业的投资总结智能体，负责综合多维度分析进行投资决策建议。

        分析框架：
        1. 多维度信号整合：技术、消息、估值、财务、资金五维分析
        2. 信号权重动态调整：根据股票类型和市场环境调整各维度权重
        3. 综合评分计算：量化投资价值和风险水平
        4. 投资建议生成：基于综合分析给出明确建议
        5. 风险控制提醒：提供投资策略和风险管理建议

        输出结构：
        ## 📊 综合分析汇总
        - 各维度分析结果回顾
        - 关键指标数据汇总

        ## ⚖️ 多维度权重
        - 各维度权重分配
        - 权重调整依据

        ## 🎯 投资评分
        - 价值评分(0-100)
        - 风险评分(0-100)
        - 综合得分计算

        ## 💡 投资建议
        - 明确的投资建议
        - 仓位配置建议
        - 操作策略指导

        ## 🛡️ 风险提示
        - 主要风险因素
        - 风险控制措施
        - 后续跟踪要点

        ## ⭐ 五维评分汇总 (各0-10)
        技术面：[X/10] - 简要理由
        消息面：[X/10] - 简要理由
        估值面：[X/10] - 简要理由
        财务面：[X/10] - 简要理由
        资金面：[X/10] - 简要理由

        综合评分：[X/10] - 基于五维评分的加权平均

        分析原则：
        - 综合考虑所有维度的信号，避免单一维度主导
        - 根据股票特征和市场环境动态调整分析权重
        - 提供客观、中性的投资建议
        - 风险提示：投资有风险，决策需谨慎

        请基于数据量化分析，给出明确的评分和建议。
        """

    async def _aggregate_stock_analysis(self, stock_code: str) -> str:
        """汇总股票综合分析数据"""
        try:
            result = f"股票{stock_code}综合分析汇总：\n\n"

            # 获取基础信息
            basic_info = await stock_data_provider.get_stock_basic_info(stock_code)
            if basic_info:
                result += f"📋 基本信息：\n"
                for key, value in list(basic_info.items())[:5]:  # 显示前5项
                    result += f"  {key}: {value}\n"
                result += "\n"

            # 获取估值数据
            valuation_data = await stock_data_provider.get_stock_valuation_data(stock_code)
            if valuation_data:
                result += f"💰 估值指标：\n"
                pe = valuation_data.get('pe', 'N/A')
                pb = valuation_data.get('pb', 'N/A')
                result += f"  市盈率: {pe}\n"
                result += f"  市净率: {pb}\n\n"

            # 获取技术指标
            technical_indicators = await stock_data_provider.get_stock_technical_indicators(stock_code)
            if technical_indicators:
                result += f"📊 技术指标：\n"
                ma5 = technical_indicators.get('ma5', 'N/A')
                rsi = technical_indicators.get('rsi', 'N/A')
                result += f"  MA5: {ma5}\n"
                result += f"  RSI: {rsi}\n\n"

            # 获取资金流向
            capital_flow = await stock_data_provider.get_stock_capital_flow(stock_code)
            if capital_flow:
                result += f"💵 资金流向：\n"
                main_inflow = capital_flow.get('main_inflow', 0)
                result += f"  主力净流入: {main_inflow:,.0f}元\n\n"

            return result

        except Exception as e:
            return f"汇总分析数据失败: {e}"

    async def _evaluate_investment_value(self, stock_code: str) -> str:
        """评估股票投资价值"""
        try:
            result = f"股票{stock_code}投资价值评估：\n\n"

            # 获取多维度数据
            valuation_data = await stock_data_provider.get_stock_valuation_data(stock_code)
            technical_data = await stock_data_provider.get_stock_technical_indicators(stock_code)
            capital_data = await stock_data_provider.get_stock_capital_flow(stock_code)

            # 计算综合评分
            score = 0
            factors = []

            # 估值评分 (40%)
            if valuation_data:
                pe = valuation_data.get('pe')
                pb = valuation_data.get('pb')

                if pe and 10 <= pe <= 25:
                    score += 30
                    factors.append("✅ 估值合理 (+30)")
                elif pe and pe < 15:
                    score += 40
                    factors.append("✅ 估值偏低 (+40)")
                elif pe and pe > 35:
                    score -= 20
                    factors.append("❌ 估值偏高 (-20)")

                if pb and pb < 2.5:
                    score += 10
                    factors.append("✅ PB合理 (+10)")

            # 技术评分 (25%)
            if technical_data:
                rsi = technical_data.get('rsi')
                if rsi and rsi < 30:
                    score += 15
                    factors.append("✅ RSI超卖 (+15)")
                elif rsi and rsi > 70:
                    score -= 10
                    factors.append("❌ RSI超买 (-10)")

                macd = technical_data.get('macd')
                macd_signal = technical_data.get('macd_signal')
                if macd is not None and macd_signal is not None:
                    if macd > macd_signal:
                        score += 10
                        factors.append("✅ MACD金叉 (+10)")

            # 资金评分 (25%)
            if capital_data:
                main_inflow_ratio = capital_data.get('main_inflow_ratio', 0)
                if main_inflow_ratio > 0.3:
                    score += 20
                    factors.append("✅ 主力资金流入 (+20)")
                elif main_inflow_ratio < -0.2:
                    score -= 15
                    factors.append("❌ 主力资金流出 (-15)")

            # 消息面评分 (10%) - 简化为中性
            score += 0
            factors.append("🤔 消息面中性 (0)")

            result += f"📊 综合评分: {score}/100\n\n"

            result += "🔍 评分因素：\n"
            for factor in factors:
                result += f"  {factor}\n"
            result += "\n"

            # 价值判断
            if score >= 70:
                value_judgment = "🌟 投资价值极高"
                recommendation = "强烈推荐买入"
            elif score >= 50:
                value_judgment = "👍 投资价值良好"
                recommendation = "建议买入或持有"
            elif score >= 30:
                value_judgment = "🤔 投资价值一般"
                recommendation = "谨慎观望"
            elif score >= 10:
                value_judgment = "👎 投资价值较低"
                recommendation = "建议减仓或卖出"
            else:
                value_judgment = "⚠️ 投资价值很低"
                recommendation = "强烈建议卖出"

            result += f"🎯 价值判断: {value_judgment}\n"
            result += f"💡 投资建议: {recommendation}\n"

            return result

        except Exception as e:
            return f"评估投资价值失败: {e}"

    async def _assess_risk_level(self, stock_code: str) -> str:
        """评估股票风险等级"""
        try:
            result = f"股票{stock_code}风险等级评估：\n\n"

            # 获取历史数据
            history_data = await stock_data_provider.get_stock_history_data(stock_code)

            risk_score = 0
            risk_factors = []

            if not history_data.empty:
                prices = history_data['收盘']

                # 计算波动率 (30%)
                if len(prices) >= 30:
                    returns = prices.pct_change().dropna()
                    volatility = returns.std() * (252 ** 0.5)  # 年化波动率

                    if volatility > 0.8:
                        risk_score += 30
                        risk_factors.append("⚠️ 波动率极高 (+30)")
                    elif volatility > 0.6:
                        risk_score += 20
                        risk_factors.append("📈 波动率较高 (+20)")
                    elif volatility > 0.4:
                        risk_score += 10
                        risk_factors.append("📊 波动率中等 (+10)")
                    else:
                        risk_score += 5
                        risk_factors.append("🛡️ 波动率较低 (+5)")

                # 计算最大回撤 (30%)
                if len(prices) >= 60:
                    rolling_max = prices.expanding().max()
                    drawdown = (prices - rolling_max) / rolling_max
                    max_drawdown = drawdown.min()

                    if max_drawdown < -0.5:
                        risk_score += 30
                        risk_factors.append("💥 历史最大回撤巨大 (+30)")
                    elif max_drawdown < -0.3:
                        risk_score += 20
                        risk_factors.append("📉 历史回撤较大 (+20)")
                    elif max_drawdown < -0.15:
                        risk_score += 10
                        risk_factors.append("📊 历史回撤中等 (+10)")

            # 估值风险 (20%)
            valuation_data = await stock_data_provider.get_stock_valuation_data(stock_code)
            if valuation_data:
                pe = valuation_data.get('pe')
                if pe and pe > 50:
                    risk_score += 20
                    risk_factors.append("💰 估值过高风险 (+20)")
                elif pe and pe > 30:
                    risk_score += 10
                    risk_factors.append("💰 估值偏高风险 (+10)")

            # 流动性风险 (20%)
            capital_data = await stock_data_provider.get_stock_capital_flow(stock_code)
            if capital_data:
                # 这里可以根据成交量和资金流向判断流动性
                risk_score += 5  # 默认中等流动性风险
                risk_factors.append("💧 流动性一般 (+5)")

            result += f"📊 风险评分: {risk_score}/100\n\n"

            result += "🔍 风险因素：\n"
            for factor in risk_factors:
                result += f"  {factor}\n"
            result += "\n"

            # 风险等级判断
            if risk_score >= 70:
                risk_level = "🔴 极高风险"
                risk_desc = "极度不稳定，适合专业投资者"
            elif risk_score >= 50:
                risk_level = "🟠 高风险"
                risk_desc = "波动较大，需谨慎投资"
            elif risk_score >= 30:
                risk_level = "🟡 中等风险"
                risk_desc = "波动适中，适合多数投资者"
            elif risk_score >= 15:
                risk_level = "🟢 较低风险"
                risk_desc = "相对稳定，较为安全"
            else:
                risk_level = "🟢 极低风险"
                risk_desc = "非常稳定，低风险投资"

            result += f"🎯 风险等级: {risk_level}\n"
            result += f"💬 风险描述: {risk_desc}\n"

            return result

        except Exception as e:
            return f"评估风险等级失败: {e}"

    async def _generate_investment_advice(self, stock_code: str) -> str:
        """生成投资建议"""
        try:
            result = f"股票{stock_code}投资建议：\n\n"

            # 获取价值评估和风险评估
            value_assessment = await self._evaluate_investment_value(stock_code)
            risk_assessment = await self._assess_risk_level(stock_code)

            # 解析评分
            value_score = 0
            risk_score = 0

            # 从价值评估中提取评分
            if "综合评分:" in value_assessment:
                try:
                    score_text = value_assessment.split("综合评分:")[1].split("/")[0].strip()
                    value_score = int(score_text)
                except:
                    pass

            # 从风险评估中提取评分
            if "风险评分:" in risk_assessment:
                try:
                    score_text = risk_assessment.split("风险评分:")[1].split("/")[0].strip()
                    risk_score = int(score_text)
                except:
                    pass

            # 计算综合建议
            net_score = value_score - risk_score * 0.3  # 风险权重30%

            result += f"📊 价值评分: {value_score}/100\n"
            result += f"⚠️ 风险评分: {risk_score}/100\n"
            result += f"🎯 综合得分: {net_score:.1f}/100\n\n"

            # 生成具体建议
            if net_score >= 60:
                advice = "🚀 强烈推荐买入"
                strategy = "可以积极买入，建议分批建仓"
                position = "可配置较高仓位 (50-80%)"
            elif net_score >= 40:
                advice = "👍 建议买入"
                strategy = "可以考虑买入，适度关注风险"
                position = "可配置中等仓位 (30-50%)"
            elif net_score >= 20:
                advice = "🤔 谨慎观望"
                strategy = "暂时观望，等待更好时机"
                position = "可保持较低仓位 (10-30%)"
            elif net_score >= 0:
                advice = "👎 建议减仓"
                strategy = "考虑减仓或卖出，控制风险"
                position = "降低至最低仓位 (<10%)"
            else:
                advice = "⚠️ 强烈建议卖出"
                strategy = "尽快卖出，停止损失"
                position = "清仓观望"

            result += f"💡 投资建议: {advice}\n"
            result += f"🎯 操作策略: {strategy}\n"
            result += f"📊 仓位建议: {position}\n\n"

            # 风险控制建议
            result += "🛡️ 风险控制：\n"
            result += "  • 分散投资，不要将所有资金投入单一股票\n"
            result += "  • 设置止损点，控制最大亏损\n"
            result += "  • 定期跟踪公司基本面变化\n"
            result += "  • 关注宏观经济环境影响\n\n"

            result += "⚠️ 重要提醒：\n"
            result += "  本建议仅供参考，不构成投资决策\n"
            result += "  投资有风险，入市需谨慎\n"
            result += "  建议咨询专业投资顾问\n"

            return result

        except Exception as e:
            return f"生成投资建议失败: {e}"


    async def _create_investment_report(self, stock_code: str, output_format: str = "text",
                                      dimension_data: Optional[Dict[str, Any]] = None) -> str:
        """创建投资分析报告
        
        Args:
            stock_code: 股票代码
            output_format: 输出格式，支持 "text" 或 "json"
            dimension_data: 各维度JSON数据字典，包含技术、消息、估值、财务、资金分析结果
        """
        try:
            if output_format == "json":
                return await self._create_json_report(stock_code, dimension_data)
            else:
                return await self._create_text_report(stock_code)

        except Exception as e:
            if output_format == "json":
                return json.dumps({"error": f"创建投资报告失败: {str(e)}"})
            else:
                return f"创建投资报告失败: {e}"

    async def _create_text_report(self, stock_code: str) -> str:
        """创建文本格式的投资分析报告"""
        result = f"📈 股票{stock_code}投资分析报告 📈\n"
        result += "=" * 50 + "\n\n"

        # 1. 基本信息汇总
        result += "1️⃣ 基本信息汇总\n"
        result += "-" * 20 + "\n"
        basic_result = await self._aggregate_stock_analysis(stock_code)
        result += basic_result + "\n"

        # 2. 投资价值评估
        result += "2️⃣ 投资价值评估\n"
        result += "-" * 20 + "\n"
        value_result = await self._evaluate_investment_value(stock_code)
        result += value_result + "\n"

        # 3. 风险等级评估
        result += "3️⃣ 风险等级评估\n"
        result += "-" * 20 + "\n"
        risk_result = await self._assess_risk_level(stock_code)
        result += risk_result + "\n"

        # 4. 投资建议
        result += "4️⃣ 投资建议\n"
        result += "-" * 20 + "\n"
        advice_result = await self._generate_investment_advice(stock_code)
        result += advice_result + "\n"

        # 5. 总结
        result += "5️⃣ 投资总结\n"
        result += "-" * 20 + "\n"
        result += "本报告基于技术分析、消息分析、估值分析、财务分析、资金分析五大维度\n"
        result += "综合评估股票的投资价值和风险水平。\n\n"
        from datetime import datetime
        result += "📅 报告生成时间: " + str(datetime.now()) + "\n"
        result += "⚠️  本报告仅供参考，投资决策请谨慎\n"

        return result

    async def _create_json_report(self, stock_code: str, dimension_data: Optional[Dict[str, Any]] = None) -> str:
        """创建JSON格式的投资分析报告
        
        Args:
            stock_code: 股票代码
            dimension_data: 各维度JSON数据字典，包含技术、消息、估值、财务、资金分析结果
        """
        import json
        from datetime import datetime
        
        # 如果有维度数据，则使用实际数据；否则使用模拟数据
        if dimension_data:
            # 从维度数据中提取评分信息
            dimension_scores = await self._extract_scores_from_dimension_data(dimension_data)
        else:
            # 获取各维度分析结果（这里需要从其他智能体获取）
            dimension_scores = await self._aggregate_dimension_scores(stock_code)
        
        comprehensive_score = await self._calculate_comprehensive_score(dimension_scores)
        radar_chart_data = await self._generate_radar_chart_data(dimension_scores)
        recommendation = await self._generate_structured_recommendation(comprehensive_score, dimension_scores)
        risk_advice = await self._generate_risk_control_advice(comprehensive_score, dimension_scores)
        confidence = await self._calculate_summary_confidence(dimension_scores)
        
        report_data = {
            "stock_code": stock_code,
            "comprehensive_analysis": {
                "overall_score": comprehensive_score,
                "dimension_scores": dimension_scores,
                "weighted_scores": {
                    "technical": 0.25,
                    "news": 0.15,
                    "valuation": 0.20,
                    "fundamental": 0.25,
                    "capital": 0.15
                },
                "investment_recommendation": recommendation["recommendation"],
                "risk_assessment": recommendation["risk_level"],
                "position_suggestion": recommendation["position"],
                "key_highlights": recommendation["highlights"]
            },
            "radar_chart_data": radar_chart_data,
            "risk_control_advice": risk_advice,
            "confidence": confidence,
            "timestamp": datetime.now().isoformat()
        }
        
        # 如果提供了维度数据，将其包含在报告中
        if dimension_data:
            report_data["dimension_data"] = dimension_data
        
        return json.dumps(report_data, ensure_ascii=False, indent=2)

    async def _aggregate_dimension_scores(self, stock_code: str) -> Dict[str, float]:
        """聚合各维度评分数据
        
        Args:
            stock_code: 股票代码
            
        Returns:
            各维度评分字典
        """
        try:
            # 尝试从其他维度智能体获取实际评分数据
            dimension_scores = {}
            
            # 技术分析评分
            try:
                technical_result = await stock_technical_analysis_agent._generate_technical_signals(
                    stock_code=stock_code, output_format="json"
                )
                if isinstance(technical_result, str):
                    technical_data = json.loads(technical_result)
                else:
                    technical_data = technical_result
                dimension_scores["technical"] = float(technical_data.get("score", 5.0))
            except Exception as e:
                self.logger.warning(f"获取技术分析评分失败: {e}")
                dimension_scores["technical"] = 5.0
            
            # 消息分析评分
            try:
                news_result = await stock_news_analysis_agent._generate_news_signals(
                    stock_code=stock_code, output_format="json"
                )
                if isinstance(news_result, str):
                    news_data = json.loads(news_result)
                else:
                    news_data = news_result
                dimension_scores["news"] = float(news_data.get("score", 5.0))
            except Exception as e:
                self.logger.warning(f"获取消息分析评分失败: {e}")
                dimension_scores["news"] = 5.0
            
            # 估值分析评分
            try:
                valuation_result = await stock_valuation_analysis_agent._generate_valuation_signals(
                    stock_code=stock_code, output_format="json"
                )
                if isinstance(valuation_result, str):
                    valuation_data = json.loads(valuation_result)
                else:
                    valuation_data = valuation_result
                dimension_scores["valuation"] = float(valuation_data.get("score", 5.0))
            except Exception as e:
                self.logger.warning(f"获取估值分析评分失败: {e}")
                dimension_scores["valuation"] = 5.0
            
            # 财务分析评分
            try:
                fundamental_result = await stock_fundamental_analysis_agent._generate_fundamental_signals(
                    stock_code=stock_code, output_format="json"
                )
                if isinstance(fundamental_result, str):
                    fundamental_data = json.loads(fundamental_result)
                else:
                    fundamental_data = fundamental_result
                dimension_scores["fundamental"] = float(fundamental_data.get("score", 5.0))
            except Exception as e:
                self.logger.warning(f"获取财务分析评分失败: {e}")
                dimension_scores["fundamental"] = 5.0
            
            # 资金分析评分
            try:
                capital_result = await stock_capital_flow_analysis_agent._generate_capital_signals(
                    stock_code=stock_code, output_format="json"
                )
                if isinstance(capital_result, str):
                    capital_data = json.loads(capital_result)
                else:
                    capital_data = capital_result
                dimension_scores["capital"] = float(capital_data.get("score", 5.0))  # 修复：使用"capital"而不是"capital_flow"
            except Exception as e:
                self.logger.warning(f"获取资金分析评分失败: {e}")
                dimension_scores["capital"] = 5.0  # 修复：使用"capital"而不是"capital_flow"
            
            self.logger.info(f"成功获取各维度评分: {dimension_scores}")
            return dimension_scores
            
        except Exception as e:
            self.logger.error(f"聚合维度评分失败: {e}")
            # 如果获取失败，返回默认评分
            return {
                "technical": 5.0,
                "news": 5.0,
                "valuation": 5.0,
                "fundamental": 5.0,
                "capital": 5.0  # 修复：使用"capital"而不是"capital_flow"
            }

    async def _calculate_comprehensive_score(self, dimension_scores: Dict[str, float]) -> float:
        """计算加权综合评分
        
        Args:
            dimension_scores: 各维度评分字典
            
        Returns:
            加权综合评分 (0-10)
        """
        # 维度权重分配
        weights = {
            "technical": 0.25,      # 技术面权重25%
            "news": 0.15,          # 消息面权重15%
            "valuation": 0.20,      # 估值面权重20%
            "fundamental": 0.25,    # 财务面权重25%
            "capital": 0.15    # 修复：使用"capital"而不是"capital_flow"
        }
        
        # 计算加权平均分
        weighted_sum = 0
        total_weight = 0
        
        for dimension, score in dimension_scores.items():
            if dimension in weights:
                weighted_sum += score * weights[dimension]
                total_weight += weights[dimension]
        
        # 确保总权重为1
        if total_weight > 0:
            comprehensive_score = weighted_sum / total_weight
        else:
            comprehensive_score = 5.0  # 默认评分
            
        return round(comprehensive_score, 2)

    async def _generate_radar_chart_data(self, dimension_scores: Dict[str, float]) -> Dict[str, Any]:
        """生成雷达图所需数据
        
        Args:
            dimension_scores: 各维度评分字典
            
        Returns:
            雷达图数据结构
        """
        # 维度名称映射
        dimension_names = {
            "technical": "技术面",
            "news": "消息面",
            "valuation": "估值面",
            "fundamental": "财务面",
            "capital": "资金面"  # 修复：使用"capital"而不是"capital_flow"
        }
        
        # 生成雷达图数据
        dimensions = []
        scores = []
        
        for dimension_key, dimension_name in dimension_names.items():
            dimensions.append(dimension_name)
            scores.append(dimension_scores.get(dimension_key, 5.0))
        
        # 计算平均分
        average_score = sum(scores) / len(scores) if scores else 5.0
        
        return {
            "dimensions": dimensions,
            "scores": scores,
            "max_score": 10,
            "average_score": round(average_score, 2)
        }

    async def _generate_structured_recommendation(self, comprehensive_score: float,
                                                 dimension_scores: Dict[str, float]) -> Dict[str, Any]:
        """生成结构化投资建议
        
        Args:
            comprehensive_score: 综合评分
            dimension_scores: 各维度评分
            
        Returns:
            结构化投资建议
        """
        # 投资建议生成逻辑
        if comprehensive_score >= 8.0:
            recommendation = "强烈推荐买入"
            risk_level = "极低风险"
            position = "50-80%仓位"
        elif comprehensive_score >= 7.0:
            recommendation = "建议买入"
            risk_level = "较低风险"
            position = "30-50%仓位"
        elif comprehensive_score >= 6.0:
            recommendation = "谨慎观望"
            risk_level = "中等风险"
            position = "10-30%仓位"
        elif comprehensive_score >= 5.0:
            recommendation = "建议减仓"
            risk_level = "较高风险"
            position = "<10%仓位"
        else:
            recommendation = "强烈建议卖出"
            risk_level = "极高风险"
            position = "清仓观望"
        
        # 生成关键亮点
        highlights = []
        for dimension, score in dimension_scores.items():
            if score >= 8.0:
                dimension_name = {
                    "technical": "技术面",
                    "news": "消息面",
                    "valuation": "估值面",
                    "fundamental": "财务面",
                    "capital": "资金面"  # 修复：使用"capital"而不是"capital_flow"
                }.get(dimension, dimension)
                highlights.append(f"{dimension_name}表现优异")
        
        if not highlights:
            highlights = ["各维度表现均衡"]
        
        return {
            "recommendation": recommendation,
            "risk_level": risk_level,
            "position": position,
            "highlights": highlights
        }

    async def _generate_risk_control_advice(self, comprehensive_score: float,
                                          dimension_scores: Dict[str, float]) -> Dict[str, Any]:
        """生成风险控制建议
        
        Args:
            comprehensive_score: 综合评分
            dimension_scores: 各维度评分
            
        Returns:
            风险控制建议
        """
        # 根据风险等级生成建议
        if comprehensive_score >= 8.0:
            advice = {
                "stop_loss": "建议设置5-8%止损点",
                "position_control": "可适当提高仓位，但仍需控制风险",
                "monitoring_focus": "重点关注技术面和资金面变化",
                "risk_warning": "虽然风险较低，但仍需注意市场整体风险"
            }
        elif comprehensive_score >= 7.0:
            advice = {
                "stop_loss": "建议设置8-10%止损点",
                "position_control": "保持中等仓位，分批建仓",
                "monitoring_focus": "关注估值面和消息面变化",
                "risk_warning": "存在一定风险，需谨慎操作"
            }
        elif comprehensive_score >= 6.0:
            advice = {
                "stop_loss": "建议设置10-12%止损点",
                "position_control": "控制仓位在较低水平",
                "monitoring_focus": "密切关注财务面和估值面",
                "risk_warning": "风险较高，建议谨慎投资"
            }
        elif comprehensive_score >= 5.0:
            advice = {
                "stop_loss": "建议设置12-15%止损点",
                "position_control": "严格控制仓位，避免重仓",
                "monitoring_focus": "重点关注风险因素变化",
                "risk_warning": "高风险投资，建议专业投资者参与"
            }
        else:
            advice = {
                "stop_loss": "建议立即止损",
                "position_control": "建议清仓观望",
                "monitoring_focus": "关注市场整体风险",
                "risk_warning": "极高风险，不建议投资"
            }
        
        return advice

    async def _extract_scores_from_dimension_data(self, dimension_data: Dict[str, Any]) -> Dict[str, float]:
        """从维度数据中提取评分信息
        
        Args:
            dimension_data: 各维度JSON数据字典
            
        Returns:
            各维度评分字典
        """
        dimension_scores = {}
        
        # ✅ 关键修复：确保dimension_data不为None
        if dimension_data is None:
            self.logger.error("❌ dimension_data为None，无法提取评分，返回默认评分")
            return {
                "technical": 5.0,
                "news": 5.0,
                "valuation": 5.0,
                "fundamental": 5.0,
                "capital": 5.0
            }
        
        # 维度映射 - 与工作流保持一致，修复维度键名不一致问题
        dimension_map = {
            "technical": "technical_analysis_json",
            "news": "news_analysis_json",
            "valuation": "valuation_analysis_json",
            "fundamental": "fundamental_analysis_json",
            "capital": "capital_flow_analysis_json"  # 修复：与工作流保持一致，使用"capital"
        }
        
        # 添加详细的调试日志
        self.logger.info(f"🔍 _extract_scores_from_dimension_data: 输入dimension_data类型={type(dimension_data)}")
        if dimension_data:
            self.logger.info(f"🔍 dimension_data键: {list(dimension_data.keys())}")
        else:
            self.logger.warning("⚠️ dimension_data为None或空")
        
        self.logger.info(f"🎯 开始提取维度评分，维度数据键: {list(dimension_data.keys())}")
        
        for dimension_key, data_key in dimension_map.items():
            # 修复：支持多种可能的字段名，确保兼容性
            possible_data_keys = [data_key]
            
            # 为capital维度添加备用字段名
            if dimension_key == "capital":
                possible_data_keys.append("capital_analysis_json")  # 备用字段名
            
            data_found = False
            for current_data_key in possible_data_keys:
                # ✅ 关键修复：确保dimension_data[current_data_key]不为None
                if current_data_key in dimension_data and dimension_data[current_data_key] is not None:
                    try:
                        # 从JSON数据中提取评分
                        data = dimension_data[current_data_key]
                        self.logger.info(f"📊 提取维度 {dimension_key} 的评分数据，数据类型: {type(data)}")
                        
                        if isinstance(data, dict):
                            self.logger.info(f"🔍 维度 {dimension_key} 数据字段: {list(data.keys())}")
                            
                            # 尝试从不同字段提取评分（按优先级）
                            score_extracted = False
                            
                            # 1. 主要字段：score
                            if "score" in data and data["score"] is not None:
                                dimension_scores[dimension_key] = float(data["score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从score字段提取到评分: {data['score']}")
                                score_extracted = True
                            
                            # 2. 备用字段：overall_score
                            elif "overall_score" in data and data["overall_score"] is not None:
                                dimension_scores[dimension_key] = float(data["overall_score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从overall_score字段提取到评分: {data['overall_score']}")
                                score_extracted = True
                            
                            # 3. 嵌套字段：analysis.score
                            elif "analysis" in data and isinstance(data["analysis"], dict):
                                if "score" in data["analysis"] and data["analysis"]["score"] is not None:
                                    dimension_scores[dimension_key] = float(data["analysis"]["score"])
                                    self.logger.info(f"✅ 维度 {dimension_key} 从analysis.score字段提取到评分: {data['analysis']['score']}")
                                    score_extracted = True
                            
                            # 4. 维度特定字段
                            elif dimension_key == "technical" and "technical_score" in data and data["technical_score"] is not None:
                                dimension_scores[dimension_key] = float(data["technical_score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从technical_score字段提取到评分: {data['technical_score']}")
                                score_extracted = True
                            
                            elif dimension_key == "news" and "news_score" in data and data["news_score"] is not None:
                                dimension_scores[dimension_key] = float(data["news_score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从news_score字段提取到评分: {data['news_score']}")
                                score_extracted = True
                            
                            elif dimension_key == "valuation" and "valuation_score" in data and data["valuation_score"] is not None:
                                dimension_scores[dimension_key] = float(data["valuation_score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从valuation_score字段提取到评分: {data['valuation_score']}")
                                score_extracted = True
                            
                            elif dimension_key == "fundamental" and "fundamental_score" in data and data["fundamental_score"] is not None:
                                dimension_scores[dimension_key] = float(data["fundamental_score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从fundamental_score字段提取到评分: {data['fundamental_score']}")
                                score_extracted = True
                            
                            elif dimension_key == "capital" and "capital_score" in data and data["capital_score"] is not None:
                                dimension_scores[dimension_key] = float(data["capital_score"])
                                self.logger.info(f"✅ 维度 {dimension_key} 从capital_score字段提取到评分: {data['capital_score']}")
                                score_extracted = True
                            
                            # 5. 其他可能的字段名
                            elif "rating" in data and data["rating"] is not None:
                                # 将rating转换为0-10评分（假设rating是1-5星）
                                rating = float(data["rating"])
                                dimension_scores[dimension_key] = rating * 2  # 转换为0-10分
                                self.logger.info(f"✅ 维度 {dimension_key} 从rating字段转换评分: {rating} -> {rating * 2}")
                                score_extracted = True
                            
                            elif "grade" in data and data["grade"] is not None:
                                # 尝试从等级字段提取评分
                                grade = str(data["grade"]).upper()
                                grade_scores = {"A": 9.0, "B": 7.0, "C": 5.0, "D": 3.0, "E": 1.0}
                                if grade in grade_scores:
                                    dimension_scores[dimension_key] = grade_scores[grade]
                                    self.logger.info(f"✅ 维度 {dimension_key} 从grade字段转换评分: {grade} -> {grade_scores[grade]}")
                                    score_extracted = True
                            
                            if not score_extracted:
                                # 如果无法提取评分，使用默认值并记录详细警告
                                dimension_scores[dimension_key] = 5.0
                                self.logger.warning(f"⚠️ 维度 {dimension_key} 无法提取评分，使用默认值5.0。数据字段: {list(data.keys())}")
                        else:
                            dimension_scores[dimension_key] = 5.0
                            self.logger.warning(f"⚠️ 维度 {dimension_key} 的数据不是字典类型: {type(data)}")
                            
                        data_found = True
                        break  # 找到数据后跳出循环
                            
                    except (ValueError, TypeError, KeyError) as e:
                        dimension_scores[dimension_key] = 5.0
                        self.logger.warning(f"❌ 维度 {dimension_key} 评分提取失败: {e}，使用默认值5.0")
                        data_found = True
                        break
            
            if not data_found:
                dimension_scores[dimension_key] = 5.0
                self.logger.warning(f"❌ 维度 {dimension_key} 数据为空或缺失，使用默认值5.0")
        
        self.logger.info(f"🎯 最终提取的维度评分: {dimension_scores}")
        return dimension_scores

    async def _calculate_summary_confidence(self, dimension_scores: Dict[str, float]) -> float:
        """计算分析置信度
        
        Args:
            dimension_scores: 各维度评分
            
        Returns:
            置信度评分 (0-1)
        """
        # 基于各维度评分的稳定性计算置信度
        scores = list(dimension_scores.values())
        
        if not scores:
            return 0.5  # 默认置信度
        
        # 计算标准差，标准差越小置信度越高
        mean_score = sum(scores) / len(scores)
        variance = sum((score - mean_score) ** 2 for score in scores) / len(scores)
        std_dev = variance ** 0.5
        
        # 标准差越小，置信度越高（0-1范围）
        # 假设标准差在0-5范围内，映射到1-0置信度
        confidence = max(0, 1 - (std_dev / 5))
        
        return round(confidence, 2)


# 全局实例
stock_investment_summary_agent = StockInvestmentSummaryAgent()